package com.qiche.service.impl;

import com.qiche.aspect.Result;
import com.qiche.mapper.StoreMemberCarMapper;
import com.qiche.model.StoreMemberCar;
import com.qiche.service.StoreMemberCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author chendezhi
 * @date 2018/3/28 17:07
 */
@Service
public class StoreMemberCarServiceImpl extends BaseService<StoreMemberCar> implements StoreMemberCarService {

    @Autowired
    private StoreMemberCarMapper storeMemberCarMapper;

    @Override
    public List<StoreMemberCar> getCarsByStoreMemberId(Long storeMemberId) {
        Example example = new Example(StoreMemberCar.class);
        //要求按创建日期降序
        example.setOrderByClause("create_time DESC");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeMemberId", storeMemberId);
        return selectByExample(example);
    }

    @Override
    public StoreMemberCar getCarsByStoreMemberIdPlateNum(Long storeMemberId, String plateNumber) {
        Example example = new Example(StoreMemberCar.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeMemberId", storeMemberId);
        criteria.andEqualTo("plateNumber", plateNumber);
        List<StoreMemberCar> storeMemberCarList = selectByExample(example);
        if (!storeMemberCarList.isEmpty()) {
            return storeMemberCarList.get(0);
        }
        return null;
    }

    @Override
    public Result saveOrUpdate(StoreMemberCar car) {
        int changeCount = 0;
        StoreMemberCar storeMemberCar = getCarsByStoreMemberIdPlateNum(car.getStoreMemberId(), car.getPlateNumber());

        if (storeMemberCar != null && car.getId().intValue()!= storeMemberCar.getId().intValue()) {
            return Result.createByErrorMessage("该车牌号码已经存在");
        }
        if (car.getId() != null) {
            changeCount = storeMemberCarMapper.updateByPrimaryKeySelective(car);

        } else {
            changeCount = storeMemberCarMapper.insert(car);
        }
        if (changeCount > 0) {
            return Result.createBySuccessMessage("更新成功");
        }
        return Result.createByErrorMessage("更新失败");
    }

    @Override
    public Result delete(Long id) {
        int deleteCount = storeMemberCarMapper.deleteByPrimaryKey(id);
        ;
        if (deleteCount > 0) {
            return Result.createBySuccessMessage("删除成功");
        }
        return Result.createByErrorMessage("删除失败");
    }
}
